<?php
include "fun.php";

$workers=[];
for ($i = 0; $i < 10; $i++) {
    workerClient();
}
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$conn = socket_connect($socket, HOST, PORT);

if (!$conn) {
    echo "err:" . socket_last_error();
    return;
}
while($f=fgets(STDIN,5)){
    $send_length=socket_write($socket,$f,strlen($f));
    echo "send:".$f."-------".strlen($f).PHP_EOL;
}
while (count($workers)) {
    if (($exit_id = pcntl_wait($status)) > 0) {
        $signo = pcntl_wtermsig($status);
        unset($workers[$exit_id]);
    }
}


function workerClient()
{
    global $workers;

    $pid = pcntl_fork();
    if ($pid < 0) exit();
    if($pid>0){
        $workers[]=$pid;
    }elseif ($pid == 0) {
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        $conn = socket_connect($socket, HOST, PORT);
        if (!$conn) {
            echo "err:" . socket_last_error();
            return;
        }
        while($receive=socket_read($socket,50,MSG_DONTWAIT)){
            echo "receive:".$receive."------".strlen($receive).PHP_EOL;
        }
    }


}












